package com.lfy.modules.common.config.sys;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.lfy.modules.common.domain.entity.SysDictionariesEntity;
import com.lfy.modules.common.mapper.SysDictionariesMapper;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
@Slf4j
public class SysDictionaries {

    private static SysDictionariesMapper mapper;
    private static  Map<String, String> cache ;

    static {
        mapper =SpringUtil.getBean(SysDictionariesMapper.class);
    }
    @PostConstruct
    public void init() {

        List<SysDictionariesEntity> sysDictionariesEntities =
                mapper.selectList(null);
        cache = sysDictionariesEntities.stream().collect(Collectors.toConcurrentMap(SysDictionariesEntity::getDictionariesKey, SysDictionariesEntity::getDictionariesValue));
        log.info("初始化系统字典数据完成");
    }

    public static String getValue(String key) {
        return cache.get(key);
    }

    public static void updateValueInMysql(String key, String value){
        SysDictionariesEntity sysDictionariesEntity = new SysDictionariesEntity();
        sysDictionariesEntity.setDictionariesValue(value);
        mapper.update(sysDictionariesEntity,new LambdaQueryWrapper<SysDictionariesEntity>().eq(SysDictionariesEntity::getDictionariesKey,key));
        cache.put(key,value);
    }
    public static void putValue(String key, String value) {
        cache.put(key, value);
    }


    public static void removeValue(String key) {
        cache.remove(key);
    }


}
